<?php

/**
 * @name PassportController
 * @desc 控制器
 */
class PassportController extends ApiBaseController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
        echo "Hello passport";
        return false;
    }

    public function checkuserAction(){
        $params = $this->post();
        $wxappConfig = SmsConfigModel::getConfByIndex('wxapp');
        $data = [
            'appid' => $wxappConfig['username'],
            'secret'    => $wxappConfig['password'],
            'code'  => trim($params['code'], '/'),
            'grant_type'    => 'authorization_code'
        ];

        $wxApp = new \Vendor\ext\Wxapp();
        $accessTokenInfo = $wxApp->webAccessToken($data);
        if(isset($accessTokenInfo['errcode'])){
            $this->ajaxReturn(400, '微信授权失败，请重新获取授权'.$accessTokenInfo['errcode']);
        }

        $data = [
            'access_token'=> $accessTokenInfo['access_token'],
            'openid'=>$accessTokenInfo['openid'],
            'lang'=> 'zh_CN'
        ];
        $wxUserInfo = $wxApp->userinfo($data);
        if(isset($wxUserInfo['errcode'])){
            $this->ajaxReturn(400, '获取微信用户信息失败,'.$wxUserInfo['errcode'], $wxUserInfo['errcode']);
        }

        //更新用户资料
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['open_id'=> $wxUserInfo['openid']]);
        if(!$userInfo){
            $this->ajaxReturn(0,'unstate');
        }

        $updateData = [
            'sex'               => isset($wxUserInfo['sex'])?$wxUserInfo['sex']: 0,
            'unionid'           => isset($wxUserInfo['unionid'])?$wxUserInfo['unionid']: 0,
            'nick_name'         => isset($wxUserInfo['nickname'])? $wxUserInfo['nickname']: 0,
            'head_img'          => isset($wxUserInfo['headimgurl'])? $wxUserInfo['headimgurl']: 0,
            'wxcity'            => isset($wxUserInfo['wxcity'])? $wxUserInfo['wxcity']: 0,
        ];
        $userModel->update(['open_id'=> $wxUserInfo['openid']], $updateData);

        $tokenData = ['user_id'=> $userInfo['user_id'], 'offline_shop_id'=> $userInfo['shop_user_id'], 'ctime'=> time()];
        //token
        $token = \Vendor\Kstring::getToken(json_encode($tokenData));
        $returnData = [
            'token'	=> $token,
            'user_id'   => $userInfo['user_id'],
            'nick'	=> $userInfo['nick_name'],
        ];
        $this->ajaxReturn(0, 'success', $returnData);
    }

    //微信公众号自动登录
    public function wxautoAction()
    {
        $params = $this->post();
        $wxappConfig = SmsConfigModel::getConfByIndex('wxapp');
        $data = [
            'appid' => $wxappConfig['username'],
            'secret'    => $wxappConfig['password'],
            'code'  => trim($params['code'], '/'),
            'grant_type'    => 'authorization_code'
        ];

        $wxApp = new \Vendor\ext\Wxapp();
        $accessTokenInfo = $wxApp->webAccessToken($data);
        if(isset($accessTokenInfo['errcode'])){
            $this->ajaxReturn(400, '微信授权失败，请重新获取授权'.$accessTokenInfo['errcode']);
        }

        $data = [
            'access_token'=> $accessTokenInfo['access_token'],
            'openid'=>$accessTokenInfo['openid'],
            'lang'=> 'zh_CN'
        ];
        $wxUserInfo = $wxApp->userinfo($data);
        if(isset($wxUserInfo['errcode'])){
            $this->ajaxReturn(400, '获取微信用户信息失败,'.$wxUserInfo['errcode'], $wxUserInfo['errcode']);
        }

        //test
//        $wxUserInfo = [
//            'open_id'   => '22222222',
//            'nick_name' => '李白',
//            'head_img'  => 'http://vmallapi.local/img/1.jpg'
//        ];

        //更新用户资料
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['open_id'=> $wxUserInfo['openid']]);
        if(!$userInfo){
            if(!isset($params['state']) || !$params['state']){
                $this->ajaxReturn(0,'unstate');
            }
            $addData = [
                'user_type'         => 0,
                'unionid'           => isset($wxUserInfo['unionid'])?$wxUserInfo['unionid']: 0,
                'open_id'           => $wxUserInfo['openid'],
                'sex'               => isset($wxUserInfo['sex'])?$wxUserInfo['sex']: 0,
                'refer_user_id'     => $params['state'],
                'nick_name'         => isset($wxUserInfo['nickname'])? $wxUserInfo['nickname']: 0,
                'head_img'          => isset($wxUserInfo['headimgurl'])? $wxUserInfo['headimgurl']: 0,
                'wxcity'            => isset($wxUserInfo['wxcity'])? $wxUserInfo['wxcity']: 0,
                'shop_user_id '     => 0,
                'shop_id'           => 0,
                'moble'             => 0,
                'login_pwd'         => rand(11111111, 99999999),
                'create_time'       => time()
            ];
//            print_r($addData);exit;
            $res = $userModel->add($addData);
            if(!$res){
                $this->ajaxReturn(400, 'er:'.$userModel->errMsg);
            }
            $userInfo = $userModel->find(['open_id'=> $wxUserInfo['openid']]);
        }

        //商品店铺ID（实体店）
        $offlineShop = $this->searchUserShopByType2($userInfo);
        $userModel->update(['user_id'=> $userInfo['user_id']], ['shop_user_id'=> $offlineShop['user_id']]);
        $tokenData = ['user_id'=> $userInfo['user_id'], 'offline_shop_id'=> $offlineShop['shop_id'], 'ctime'=> time()];
        //token
        $token = \Vendor\Kstring::getToken(json_encode($tokenData));

        $returnData = [
            'token'	=> $token,
            'user_id'   => $userInfo['user_id'],
            'nick'	=> $userInfo['nick_name'],
        ];
        $this->ajaxReturn(0, 'success', $returnData);
    }

    public function LoginAction()
    {
        $params = $this->post();

        $rule = [
            'moble'     => 'require|regex:moble',
            'login_pwd' => 'require|regex:login_pwd',
        ];
        $msg = [
            'moble.require' => '必须输入手机号',
            'moble.regex'   => '必须正确的手机号码',
            'login_pwd.require' => '必须输入密码',
            'login_pwd.regex'   => '密码格式错误',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['moble'=> $params['moble']]);

        if(!$userInfo){
            $this->ajaxReturn(400, '手机号码未注册');
        }
        if(md5($params['login_pwd']) != $userInfo['login_pwd']){
            $this->ajaxReturn(400, '密码错误');
        }
        if($userInfo['status'] != 1){
            $this->ajaxReturn(400, '账户禁止登录');
        }

        //商品店铺ID（实体店）
        $offlineShop = $this->searchUserShopByType2($userInfo);
        $tokenData = ['user_id'=> $userInfo['user_id'], 'offline_shop_id'=> $offlineShop['shop_id'], 'ctime'=> time()];
        //token
        $token = \Vendor\Kstring::getToken(json_encode($tokenData));

//        $config = \Yaf\Application::app()->getConfig()->app;
        $returnData = [
            'token'	=> $token,
            'user_id'   => $userInfo['user_id'],
            'nick'	=> $userInfo['nick_name'],
        ];
        $this->ajaxReturn(0, 'success', $returnData);
    }

    //查找用户最顶层实体店（用户显示商品）
    private $offline_shop;
    private function searchUserShopByType2($user){
        if(!$user || empty($user)){
            return false;
        }
        //查询推荐店铺
        $userInfo = UserModel::getSingleton()->db
            ->alias('u')
            ->field('u.user_id, u.refer_user_id, s.shop_id, s.shop_type')
            ->join(['shop', 's'], ['u.shop_id'=> 's.shop_id'], 'left join')
            ->where_c(['u.user_id'=> $user['refer_user_id']])
            ->find();

        if($userInfo['shop_type'] != 2){
            $this->searchUserShopByType2($userInfo);
        } else {
            $this->offline_shop = $userInfo;
        }

        return $this->offline_shop ;
    }

    public function registerAction()
    {
        $params = $this->post();

        $rule = [
            'moble'     => 'require|regex:moble',
            'nick_name' => 'require|length:1,8',
            'login_pwd' => 'require|regex:login_pwd',
            'pay_pwd'   => 'require|regex:pay_pwd',
//            'refer_user_id' => 'require|integer|gt:0',
            'self_user_id'    => 'require|integer|gt:0',
            'sms_code' => 'require',
            'path'      => 'require|in:1,2'
        ];
        $msg = [
            'moble.require' => '必须输入手机号',
            'moble.regex'   => '必须正确的手机号码',
            'nick_name.require'     => '必须输入2~8昵称',
            'nick_name.length'  => '昵称必须在2~8位之间',
            'login_pwd.require' => '必须设置登录密码',
            'login_pwd.regex'   => '登录密码必须6~16位',
            'pay_pwd.require' => '必须设置支付密码',
            'pay_pwd.regex'   => '支付密码必须6~16位',
//            'refer_user_id.require' => '必须输入推荐码',
//            'refer_user_id.integer' => '推荐人信息异常',
//            'refer_user_id.gt' => '推荐人信息异常',
            'self_user_id.require' => '请重新获取分享二维码',
            'self_user_id.integer' => '请重新获取分享二维码',
            'self_user_id.gt' => '请重新获取分享二维码',
            'sms_code.require' => '必须输入短信验证码',
            'path.require'      => '未获取到通道信息',
            'path.in'      => '通道信息错误',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

//        if($params['refer_user_id']<=1000){
//            $this->ajaxReturn(400, '错误的推荐码');
//        }
//        $params['refer_user_id'] = $params['refer_user_id'] - 1000;

        $userModel = UserModel::getSingleton();
        //验证推荐码是否存在
        if($userModel->find(['moble'=> $params['moble']])){
            $this->ajaxReturn(400, '手机号已被注册');
        }
        //分享人ID
        $self_user_id = $params['self_user_id'] - 1000;
        $selfUserInfo = $userModel->find(['user_id'=> $self_user_id]);
        if(!$selfUserInfo){
            $this->ajaxReturn(400, '分享人不存在。');
        }
        //动态获取refer
        $topChild = $userModel->findAll(['refer_user_id'=> $self_user_id],'*','user_id asc');
        //获取左通道挂链人
        $refer_user_id = 0;
        if($params['path'] == 1){
            if(count($topChild)==0){
                $refer_user_id = $self_user_id;
            }elseif(count($topChild)<=1){
//                $refer_user_id = $self_user_id;
                $refer_user_id = $userModel->getReferTeamUser($topChild[0]);
            }else {
                $refer_user_id = $userModel->getReferTeamUser($topChild[0]);
            }
        }
        //获取右通道挂链人
        if($params['path'] == 2){
            if(count($topChild)==0){
                $refer_user_id = $self_user_id;
            }elseif(count($topChild)==1){
//                $refer_user_id = $userModel->getReferTeamUser($topChild[0]);
                $refer_user_id = $self_user_id;
            }else {
                $refer_user_id = $userModel->getReferTeamUser($topChild[1]);
            }
        }

        if(!$refer_user_id){
            $this->ajaxReturn(400, '注册失败。');
        }

        $referUserInfo = $userModel->find(['user_id'=> $refer_user_id]);
        if($referUserInfo['refer_num']>=2){
            $this->ajaxReturn(400, '推荐次数超限');
        }

        $params['nick_name'] = trim($params['nick_name']);
        $params['login_pwd'] = md5(trim($params['login_pwd']));
        $params['pay_pwd'] = md5(trim($params['pay_pwd']));
        $params['refer_user_id'] = $refer_user_id;
        $params['self_refer_num'] = 0;

        //是否直推
        $is_self_refer = ($self_user_id==$params['refer_user_id'])? 1 :0;
        unset($params['self_user_id']);

        $sms = new \Vendor\ext\Sms();
        if($sms->checkSms($params['moble'], $params['sms_code'])){
            $this->ajaxReturn(400, $sms->errMsg);
        }

        try{
            \Vendor\DB::startTrans();
            //注册
            if(!$userModel->add($params)){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '注册失败');
            }
            //更新推荐次数
/*            if(!$userModel->setInc(['user_id'=> $referUserInfo['user_id']], 'refer_num')){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '注册失败1');
            }*/
            $refer_num = $referUserInfo['refer_num'] + 1;
            $self_refer_num = $referUserInfo['self_refer_num'] + $is_self_refer;
            if(!$userModel->update(
                ['user_id'=> $referUserInfo['user_id']],
                ['refer_num'=> $refer_num, 'self_refer_num'=> $self_refer_num])){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '注册失败1');
            }

            \Vendor\DB::commit();
        }catch(\Yaf\Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '注册失败');
        }

        $this->ajaxReturn(0, '注册成功');
    }

    //发送短信
    public function smsAction(){

        $params = $this->post();

        $rule = [
            'moble'     => 'require|regex:moble',
            'type' => 'require|in:reg,findpwd,findpwd_pay,edit_moble',
        ];
        $msg = [
            'moble.require' => '必须输入手机号',
            'moble.regex'   => '必须正确的手机号码',
            'type.require'  => '必须指定发送类型',
            'type.in'       => '错误的发送类型'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //如果是注册和修改密码判断手机号是否存在
        if(in_array($params['type'], ['reg', 'edit_moble'])){
            $userModel = UserModel::getSingleton();
            $exist = $userModel->find(['moble'=> $params['moble']], 'user_id');
            if($exist){
                $this->ajaxReturn(400, '手机号已经存在');
            }
        }

        $code = rand(1111, 9999);
        $sms = new \Vendor\ext\Sms();
        $res  = $sms->send($params['moble'], $code, $params['type'], $params['type']);
        if(!isset($res[1])){
            $this->ajaxReturn(400, $res[0]);
        }
        $this->ajaxReturn(0, '发送成功');
    }

    //修改密码
    public function resetpwdAction()
    {
        $params = $this->post();
        $rule = [
            'moble'     => 'require|regex:moble',
            'sms_code'  => 'require',
            'npwd'      => 'require|regex:pay_pwd',
            'type'      => 'require|in:findpwd,findpwd_pay'
        ];
        $msg = [
            'moble.require' => '必须输入手机号',
            'moble.regex'   => '手机号格式错误',
            'sms_code.require'  => '必须输入短信验证码',
            'npwd.require'  => '必须输入新密码',
            'npwd.regex'    => '新密码格式错误',
            'type.require'  => '未获取到密码类型',
            'type.in'       => '错误的密码类型'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        if($params['type'] == 'findpwd' && !preg_match('/^[a-zA-Z0-9]{6,16}$/', (string) $params['npwd'])){
            $this->ajaxReturn(400, '登录密码必须6~16位');
        }
        if($params['type'] == 'findpwd_pay' && !preg_match('/^[\d]{6}$/', (string) $params['npwd'])){
            $this->ajaxReturn(400, '支付密码必须6~16位');
        }

        //验证手机号是否正确
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['moble'=> $params['moble']]);
        if(!$userInfo['moble']){
            $this->ajaxReturn(400, '手机号码错误');
        }

        $sms = new \Vendor\ext\Sms();
        if($sms->checkSms($params['moble'], $params['sms_code'], $params['type'])){
            $this->ajaxReturn(400, $sms->errMsg);
        }

        $e_type = [
            'findpwd'   => 'login_pwd',
            'findpwd_pay'   => 'pay_pwd',
        ];

        if(!$userModel->update(['moble'=> $params['moble']],
            [
                $e_type[$params['type']]=> md5($params['npwd']),
                'update_time'=> time()
            ]
        )){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, 'success');
    }

}
